package com.haima.sage.bigdata.api.process.impl;

import com.haima.sage.bigdata.api.common.DbUtils;
import com.haima.sage.bigdata.api.entity.storage.Storage;
import com.haima.sage.bigdata.api.exception.ValidateException;
import com.haima.sage.bigdata.api.process.ParamProcess;
import com.haima.sage.bigdata.api.vo.param.RowParam;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.util.List;

public class RowParamProcess extends ParamProcess {
    private static final Logger LOG = LogManager.getLogger(RowParamProcess.class);
    private RowParam param;
    public RowParamProcess(RowParam param) {
        this.param = param;
    }

    protected Object executeES(Storage storage, String table, String pattern, Integer maxBatchSize) throws Exception {
        super.executeES(storage, table, pattern, maxBatchSize);
        String entity = genEsJson(table,maxBatchSize, storage);
        Object obj = null;
        try {
            obj = esUtils.esPost(storage, table, maxBatchSize, entity, param);
        } catch (Exception e) {
            throw new Exception("ES post error!");
        }
        return ((List) obj).get(0);
    }

    protected Object executeRedis(Storage storage, String table, Integer maxBatchSize) {
        return null;
    }

    @Override
    public void validate() throws ValidateException {
        super.validate(param);
        validateFields(param.getFields());
    }

    protected Object executeDB(Storage storage, String table, Integer maxBatchSize) throws Exception {
        String sql = genSQL(table);
        try (Connection conn = DbUtils.getConnection(storage.getId())) {
            return DbUtils.getRowResult(sql, conn);
        }
    }
    /**
     * select * from ${table}
     * where ${where}
     * @param table
     */
    private String genSQL(String table) throws ValidateException {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        if (isFieldsValid(param.getFields())) {
            for (String field : param.getFields()) {
                sql.append(field).append(",");
            }
            sql.deleteCharAt(sql.length() - 1);
        } else {
            sql.append("*");
        }
        sql.append(" FROM ").append(table);
        // where
        appendWhere(sql, param.getWhere());
        return sql.toString();
    }

    /**
     * select * from ${table}
     * where ${where}
     * @param table
     */
    private String genEsJson(String table, Integer maxBatchSize, Storage storage) throws Exception{
        StringBuilder jsonBody = new StringBuilder();
        jsonBody.append("{");

        if (param.getFields() != null)
            esUtils.appendField(jsonBody, param.getFields());

        //query
        if(param.getWhere() != null) {
            jsonBody.append("\"query\":");
            esUtils.appendWhere(jsonBody,table, storage, param.getWhere());
        }
        jsonBody.append("\"size\": 1,");
        //sort
        //esUtils.appendOrderBy(jsonBody,param.getOrderBy());
        jsonBody.deleteCharAt(jsonBody.length() - 1);
        jsonBody.append("}");
        LOG.info(jsonBody.toString());
        return jsonBody.toString();
    }

}
